﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;

namespace auxiliary_proj
{
    public partial class FormUserUpdate : Form
    {
        Parser p;
        byte[] image_arr;

        //server connection stuff
        private static MySqlConnection connection;
        private static MySqlCommand comm;
        MemoryStream ms;

        public FormUserUpdate()
        {
            InitializeComponent();
            Home home = Singleton.getHome();
            pBoxUpdate.Image = home.picUser.Image;
            pBoxUpdate.SizeMode = PictureBoxSizeMode.StretchImage;
            this.tbFirstName.Text = home.lbfName.Text;
            this.tbLastName.Text = home.lbLastName.Text;
            this.tbEmail.Text = home.lblEmail.Text;

            p = new Parser();
        }

        private void pBoxUpdate_Click(object sender, EventArgs e)
        {
            PictureBox p = sender as PictureBox;
            if (p != null)
            {
                //file open dialog box
                OpenFileDialog ofd = new OpenFileDialog();
                //Filter images in the open file dialog
                ofd.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG|All files (*.*)|*.*";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    //display the image on the picture box
                    p.Image = Image.FromFile(ofd.FileName);
                    p.SizeMode = PictureBoxSizeMode.StretchImage;
                }
            }
        }

        private void btnSubmit_Click(object sender, EventArgs e)
        {
            if (pBoxUpdate.Image != null)
            {
                if ((tbFirstName.Text != "") && (tbLastName.Text != "") && (tbEmail.Text != ""))
                {
                    if (p.testEmailRegex(tbEmail.Text))
                    {
                        //parse the server file
                        Program.parseServerInfo();

                        //establish a connection to the server.
                        connection = new MySqlConnection(Program.getConnection());

                        convert_photo();
                        //update query
                        string update = "UPDATE USER SET first_name = '" + tbFirstName.Text + "', last_name = '" + tbLastName.Text + "', email = '" + tbEmail.Text + "', photo = @photo where user_name = '" + Employee.User + "'";

                        comm = new MySqlCommand(update, connection);
                        comm.Parameters.AddWithValue("@photo", image_arr);

                        Cursor.Current = Cursors.WaitCursor;
                        try
                        {
                            connection.Open();
                            try
                            {
                                //Write image to the database
                                int record = comm.ExecuteNonQuery();
                                Singleton.getHome().picUser.Image = pBoxUpdate.Image;
                                Singleton.getHome().lbfName.Text = tbFirstName.Text;
                                Singleton.getHome().lbLastName.Text = tbLastName.Text;
                                Singleton.getHome().lblEmail.Text = tbEmail.Text;
                                if (record > 0)
                                {
                                    MessageBox.Show("User Updated!", "Successful", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                else
                                    MessageBox.Show("Failed to Update User!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            catch (MySqlException ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                        }
                        catch (DataException ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                        finally
                        {
                            connection.Close();
                        }
                        Cursor.Current = Cursors.Default;
                        this.Close();
                    }
                    else MessageBox.Show("Invalid Email", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else MessageBox.Show("Invalid Entry (*Missing Field(s))", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else MessageBox.Show("Profile Image Missing!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public void convert_photo()
        {
            if (pBoxUpdate != null)
            {
                ms = new MemoryStream();
                pBoxUpdate.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                image_arr = ms.ToArray();
            }
        }

        private void btnPassword_Click(object sender, EventArgs e)
        {
            //new form that verifies old password, then asks user to enter new pass and re-type for validation

            Singleton.showForm<FormChangePass>(Application.OpenForms);
        }

        private void this_formClosing(object sender, FormClosingEventArgs e)
        {
            //this form is closing, also close children (FormChangePass, )
            List<Form> close = new List<Form>();

            foreach (Form f in Application.OpenForms)
            {
                if (f is FormChangePass)
                    close.Add(f);
            }

            foreach (Form f in close)
            {
                f.Close();
                f.Dispose();
            }
        }
    }
}
